package com.junmo.fanbizhidemo.demoview;

import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.junmo.fanbizhidemo.R;
import com.universalvideoview.UniversalMediaController;
import com.universalvideoview.UniversalVideoView;

import java.util.Formatter;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.widget.Toast.makeText;

public class VideoActivity extends AppCompatActivity implements UniversalVideoView.VideoViewCallback {

    @BindView(R.id.videoView)
    UniversalVideoView videoView;
    @BindView(R.id.media_controller)
    UniversalMediaController mediaController;
    @BindView(R.id.video_layout)
    FrameLayout videoLayout;


    private boolean isFullscreens;//是否全屏

    private int cachedHeight;//播放器高度

    private int mSeekPosition;//续播的断点

    private ConnectivityManager manager;

    private static final String SEEK_POSITION_KEY = "SEEK_POSITION_KEY";

    //将长度转换为时间
    StringBuilder mFormatBuilder;
    Formatter mFormatter;

    private long TIME = 60000 * 5;

    private CountDownTimer downTimer = new CountDownTimer(TIME, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            Log.e("downTimer-->", "onTick");
        }

        @Override
        public void onFinish() {
            Log.e("downTimer-->", "onFinish");
            purchase();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        ButterKnife.bind(this);
        videoView.setMediaController(mediaController);

        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
        //设置视频区域大小
        setVideoAreaSize();
        //设置监听
        setOnListener();
    }

    //设置购买花朵
    private void purchase() {
        videoView.suspend();
    }

    private void setVideoAreaSize() {
        videoLayout.post(new Runnable() {
            @Override
            public void run() {
                int width = videoLayout.getWidth();
                cachedHeight = (int) (width * 450f / 720f);
                ViewGroup.LayoutParams layoutParams = videoLayout.getLayoutParams();
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                layoutParams.height = cachedHeight;
                videoLayout.setLayoutParams(layoutParams);
                videoView.setVideoPath("http://womenchildtupian.b0.upaiyun.com/1d46b8ddfb1dcaba2f9e23c25bba277a.mp4");
//                videoView.start();
                checkNetworkState();
            }
        });
    }

    private void setOnListener() {
        videoView.setVideoViewCallback(this);
    }

    private void checkNetworkState() {
        boolean flag = false;
        //得到网络连接信息
        manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        //去进行判断网络是否连接
        if (manager.getActiveNetworkInfo() != null) {
            flag = manager.getActiveNetworkInfo().isAvailable();
        }
        if (!flag) {
            makeText(this, "请检查网络是否连接", Toast.LENGTH_SHORT).show();
        } else {
            isNetworkAvailable();
        }
    }

    /**
     * 网络已经连接，然后去判断是wifi连接还是GPRS连接
     */
    private void isNetworkAvailable() {

        NetworkInfo.State gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        if (NetworkInfo.State.CONNECTED == gprs || NetworkInfo.State.CONNECTING == gprs) {
//            makeText(this, "您当前正在使用流量", Toast.LENGTH_SHORT).show();
            AlertDialog dialog = new AlertDialog.Builder(this).setTitle("提示")
                    .setMessage("您正在使用流量，是否继续？")
                    .setPositiveButton("继续播放", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            videoView.start();
                            downTimer.start();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).create();
            dialog.show();
        } else {
            videoView.start();
            downTimer.start();
        }
    }

    @Override
    public void onScaleChange(boolean isFullscreen) {
        isFullscreens = isFullscreen;
        if (isFullscreen) {
            ViewGroup.LayoutParams layoutParams = videoLayout.getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            videoLayout.setLayoutParams(layoutParams);
//                    bottomLayout.setVisibility(View.GONE);
        } else {
            ViewGroup.LayoutParams layoutParams = videoLayout.getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.height = cachedHeight;
            videoLayout.setLayoutParams(layoutParams);
//                    bottomLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPause(MediaPlayer mediaPlayer) { // 视频暂停
//        String time = stringForTime(videoView.getCurrentPosition());
//        Log.e("播放时间time", time);
        TIME = TIME - videoView.getCurrentPosition();   //重新计算倒计时时间

    }


    @Override
    public void onStart(MediaPlayer mediaPlayer) { // 视频开始播放或恢复播放
        downTimer.start();
    }

    @Override
    public void onBufferingStart(MediaPlayer mediaPlayer) {// 视频开始缓冲
    }

    @Override
    public void onBufferingEnd(MediaPlayer mediaPlayer) {// 视频结束缓冲
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (videoView != null && videoView.isPlaying()) {
            mSeekPosition = videoView.getCurrentPosition();
            videoView.pause();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SEEK_POSITION_KEY, mSeekPosition);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mSeekPosition = savedInstanceState.getInt(SEEK_POSITION_KEY);
    }

    @Override
    public void onBackPressed() {
        if (this.isFullscreens) {
            videoView.setFullscreen(false);
        } else {
            super.onBackPressed();
        }

    }

    /**
     * 将播放长度转化为时间
     *
     * @param timeMs
     * @return
     */
    private String stringForTime(int timeMs) {

        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }


}
